package com.alien.admin.context.task.impl;

import com.alien.admin.context.task.TaskQueue;
import com.alien.admin.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: zsy
 * @Date: 2021/10/28 11:36
 */
@Component
public class TaskQueueImpl implements TaskQueue {
    @Value("${deployServer.queue}")
    private String queueName;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    private String CANCEL_KEY_NAME = "cancel-rec-list";

    @Override
    public void putTaskToQueue(Long recId) {
        if(recId != null) {
            redisTemplate.opsForSet().add(queueName, recId);
        }
    }

    @Override
    public Long getTaskId() {
        Long recId = (Long)redisTemplate.opsForSet().pop(queueName);
        return recId;
    }

    @Override
    public void appendCancelTask(List<Long> recIdList) {
        SetOperations<Object, Object> kvSetOperations = redisTemplate.opsForSet();
        recIdList.stream().forEach(recId -> kvSetOperations.add(CANCEL_KEY_NAME, recId));

        // 设置过期,防止无效值积压
        Date expiredDate = DateUtil.getMinuteDate(30);
        redisTemplate.expireAt(CANCEL_KEY_NAME, expiredDate);
    }

    @Override
    public boolean isCancelTask(Long recId) {
        Boolean canceled = redisTemplate.opsForSet().isMember(CANCEL_KEY_NAME, recId);
        return canceled;
    }
}
